package cn.highedu.server;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 处理客户请求的线程
 */
public class ClientHandler implements Runnable {
    private Socket socket;
    public ClientHandler(Socket clientSocket){
        socket = clientSocket;
    }

    /**
     * 从请求中读取一行文本数据
     * @return 一行
     */
    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        char previous = 0;
        char current = 0;
        int b;
        while ((b=in.read())!=-1){
            current = (char) b;
            if (previous == '\r' && current == '\n'){
                //遇到回车就结束
                break;
            }else if(current != '\r' && current != '\n'){
                builder.append(current);
            }
            previous = current;
        }
        return builder.toString();
    }
    @Override
    public void run() {
        try {
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            //接收请求
            //读取请求行
            String requestLine =readLine();
            System.out.println(requestLine);
            String[] line = requestLine.split("\\s");
            String method = line[0];
            String uri = line[1]; //网页 路径
            String protocol = line[2];
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);
            //读取请求头
            String requestHeader;
            //循环读取到空行结束
            while (!(requestHeader = readLine()).isEmpty()){
                System.out.println(requestHeader);
            }
            //定位静态资源路径
            File root = new File(
                    ClientHandler.class.getClassLoader().getResource(".").toURI()
            );
            //显示规范路径
            System.out.println(root.getCanonicalPath());
            //定位静态文件夹
            File staticDir = new File(root, "static");
            System.out.println(staticDir);
            //定位到静态文件
            File file = new File(staticDir, uri);// uri /  /index.html /demo.html
            //file.exists()//检查文件是否存在
            //不能使用 file.exists() 检查是否存在，文件夹时候，也会出现存在
            System.out.println(file); // static/
            String statusLine = "HTTP/1.1 200 OK";
            if (! file.isFile()){
                //返回404.html
                file = new File(staticDir, "404.html");
                statusLine = "HTTP/1.1 404 Not Found";
            }
            //读取文件的全部内容，就是文件的全部字节
            byte[] body = new byte[(int)file.length()];
            //打开文件
            FileInputStream fis = new FileInputStream(file);
            //从文件读取尽可能多的字节到数组（这里读取了全部字节）
            fis.read(body);

            //发送响应
//            String html = "<html>" +
//                    "<head>" +
//                    "<title>Demo</title>" +
//                    "</head>" +
//                    "<body>Client Handler</body>" +
//                    "</html>";
//            byte[] body = html.getBytes(StandardCharsets.UTF_8);
            out.write(statusLine.getBytes(StandardCharsets.ISO_8859_1));
            out.write('\r');
            out.write('\n');
            out.write("Content-Type: text/html; charset=utf-8".getBytes(StandardCharsets.ISO_8859_1));
            out.write('\r');
            out.write('\n');
            out.write(("Content-Lenght: "+body.length).getBytes(StandardCharsets.ISO_8859_1));
            out.write('\r');
            out.write('\n');
            out.write('\r');
            out.write('\n');
            out.write(body);
            in.close();
            out.close();
            socket.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
